package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.enums.BizEnum;
import com.qk.common.util.CurrentUserHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;


    //@Around("@annotation(com.qk.management.annotation.LogOperation)")
    @Around("execution(* com.qk.management.controller.*.add*(..)) || " +
            "execution(* com.qk.management.controller.*.delete*(..)) ||" +
            "execution(* com.qk.management.controller.*.update*(..)) ")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            long startTime = System.currentTimeMillis();
            Object[] args = joinPoint.getArgs();
            String methodParams = JSONUtil.toJsonStr(args);
            result = joinPoint.proceed();
            long costTime = System.currentTimeMillis() - startTime;
            OperateLog operateLog = OperateLog.builder()
                    .operateUserId(CurrentUserHolders.getCurrentUserId())
                    .operateTime(LocalDateTime.now())
                    .className(joinPoint.getTarget().getClass().getName())
                    .methodName(joinPoint.getSignature().getName())
                    .methodParams(methodParams)
                    .returnValue(JSONUtil.toJsonStr(result))
                    .costTime(costTime)
                    .build();
            try {
                operateLogMapper.insert(operateLog);
            }catch (Exception e){
                log.error("日志插入失败:{}", e.getMessage());
            }
        } catch (Throwable e) {
            log.error("日志记录异常:{}", e.getMessage());
            result = Result.error(BizEnum.GENERATE_ERROR.getMsg());
        }
        return result;
    }
    
}